package net.ix.util.net;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class Get{
	private static String tag = "Get";
	
	public static String UNICODECHARSET = "UTF-8";
	private String uriStr;
	private URI uri;
	private int statusCode;
	private HttpEntity entity;
	private HttpGet get;
	private String entityContent;
	
	public Get(){
	}
	public Get(URI uri){
		setUri(uri);
	}
	public Get(String uriString){
		setUri(uriString);
	}
	
	public void setUri(URI u){
		uri = u;
	}
	public void setUri(String u){
		uriStr = u;
		try {
			uri = new URI(uriStr);
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}
	public void connect(){
		get = new HttpGet(uri);
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		
		HttpResponse response;
		
		try {
			Log.i(tag, "executing request " + get.getRequestLine());
			response = httpclient.execute(get);
			Log.i(tag, "http status is " + response.getStatusLine().getStatusCode());
			
			statusCode = response.getStatusLine().getStatusCode();
			entity = response.getEntity();
			if(entity != null){
				entityContent = EntityUtils.toString(entity, UNICODECHARSET);
			}
		} catch (ClientProtocolException e) {
			Log.e(tag, e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			Log.e(tag, e.getMessage());
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}
	public int getStatusCode(){
		return statusCode;
	}
	public String getContent(){
		return entityContent;
	}
	public HttpEntity getEntity(){
		return entity;
	}
}